package com.yuanfeng.goods.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.collect.Lists;
import com.yuanfeng.commoms.config.YFConfig;
import com.yuanfeng.commoms.exception.BizCodeEnume;
import com.yuanfeng.commoms.util.ParseMapUtils;
import com.yuanfeng.commoms.util.ParseTokenUtils;
import com.yuanfeng.commoms.util.RedisUtil;
import com.yuanfeng.commoms.util.ResponseResult;
import com.yuanfeng.commoms.util.querypage.PageUtils;
import com.yuanfeng.commoms.util.querypage.Query;
import com.yuanfeng.commoms.vo.goods.GdsListQueryResultVO;
import com.yuanfeng.commoms.vo.user.UserInfoVO;
import com.yuanfeng.goods.dto.CartGuessLikeGoodsQueryDTO;
import com.yuanfeng.goods.dto.WapUserFootPrintDTO;
import com.yuanfeng.goods.entity.GoodsUserFootprintEntity;
import com.yuanfeng.goods.mapper.GoodsCommonMapper;
import com.yuanfeng.goods.mapper.GoodsUserFootprintMapper;
import com.yuanfeng.goods.service.GoodsUserFootprintService;
import com.yuanfeng.goods.vo.WapCommonBaseUserFootVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @ClassName GoodsUserFootprintServiceImpl
 * @Description  商品访问足迹表
 * @Author cyp
 * @Date 2023-06-08 10:01:59
 * @Version 1.0
 **/
@Service
public class GoodsUserFootprintServiceImpl extends ServiceImpl<GoodsUserFootprintMapper, GoodsUserFootprintEntity>
        implements GoodsUserFootprintService {

    @Autowired
    private GoodsCommonMapper getGoodsCommonMapper;
    @Autowired
    private GoodsCommonMapper goodsCommonMapper;

    @Override
    public ResponseResult queryCartGuessLikeGoods(CartGuessLikeGoodsQueryDTO param) {
        List<GdsListQueryResultVO> results = Lists.newArrayList();
        Integer limitSize = param.getLimitSize();
        UserInfoVO userInfo = ParseTokenUtils.getUserInfoByToken(param.getToken());

        // 查询用户足迹商品 的所属分类
        List<Integer> catIds = this.baseMapper.selectCartGuessLikeGoods(limitSize, userInfo.getUserId());
        param.setCatIds(catIds);
        results = goodsCommonMapper.selectUserFoot(param);

        return ResponseResult.success(results);
    }

    @Override
    public ResponseResult queryUserFoot(WapUserFootPrintDTO param) {
        IPage<WapCommonBaseUserFootVO> page = null;

        try {
            // 获取用户id
            String userIdStr = RedisUtil.get(YFConfig.YF_USER_TOKEN_USERID + param.getToken());

            if (null == userIdStr || userIdStr.equals("")) {
                return ResponseResult.fail(BizCodeEnume.TOKEN_IS_INVALID);
            }
            Map data = ParseMapUtils.beanToMap(param);
            param.setUserId(userIdStr);
            // 查询commodIds
            List<Integer> commonIds = this.baseMapper.selectUserFoot(param);
            if (!CollectionUtils.isEmpty(commonIds)) {
                param.setCommonIds(commonIds);

                page = getGoodsCommonMapper.selectByCommonIds(new Query<WapCommonBaseUserFootVO>().getPage(data), param);
            } else {
                page = new Query<WapCommonBaseUserFootVO>().getPage(data);
            }
            return ResponseResult.success(PageUtils.getPage(page));
        } catch (Exception e) {
            return ResponseResult.fail(e.getMessage());
        }
    }

    @Override
    public ResponseResult deleteFootPrint(Map<String, Object> map) {
        UserInfoVO userInfoVO = ParseTokenUtils.getUserInfoByToken(map.get("token").toString());

        if (userInfoVO == null) {
            return ResponseResult.fail(BizCodeEnume.TOKEN_IS_INVALID);
        }
        map.put("userId", userInfoVO.getUserId());
        List list = (List) map.get("commonIds");
        this.baseMapper.delete(new LambdaQueryWrapper<GoodsUserFootprintEntity>()
                       .eq(GoodsUserFootprintEntity::getUserId,userInfoVO.getUserId())
                       .in(map.containsKey("commonIds"),GoodsUserFootprintEntity::getCommonId,list));
        return ResponseResult.success();
    }

    @Override
    public ResponseResult queryUserRandomGoods(Map<String, Object> map) {
        ResponseResult resp = new ResponseResult();
        // 获取用户id
        String userIdStr = RedisUtil.get(YFConfig.YF_USER_TOKEN_USERID + map.get("token"));
        List<Integer> catIds = new ArrayList<>();
        if (null != userIdStr) {
            //根据用户id查询足迹 得出用户访问的最近10个商品分类
            List<GoodsUserFootprintEntity> list = this.baseMapper.selectList(new LambdaQueryWrapper<GoodsUserFootprintEntity>()
                    .eq(GoodsUserFootprintEntity::getUserId, userIdStr)
                    .groupBy(GoodsUserFootprintEntity::getCatId)
                    .orderByDesc(GoodsUserFootprintEntity::getFootprintTime)
                    .last("LIMIT 10"));

            catIds = list.stream().map(GoodsUserFootprintEntity::getCatId).collect(Collectors.toList());

        }
        //根据分类id随机查询10款商品
        List<Map<String, Object>> resultMap;
        if (map.get("shopId") != null && map.get("shopId") != ""){
            resultMap = this.baseMapper.queryCatRandomGoods(catIds, (Integer) map.get("shopId"));
        }else {
            resultMap = this.baseMapper.queryCatRandomGoods1(catIds);
        }

        resp.setCode(1);
        resp.setData(resultMap);
        return resp;
    }
}
